package com.firefighting.controller;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.ActionMap;
import javax.xml.crypto.Data;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.firefighting.entity.User;
import com.firefighting.entity.UserBasicInfo;
import com.firefighting.service.ContractService;
import com.firefighting.service.ReportService;
import com.firefighting.service.UserBasicInfoService;
import com.firefighting.util.Cover;
import com.firefighting.util.CreatePDFJuge;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
@Controller
@RequestMapping("/MaintenanceReport")
public class MaintenanceReportController {
	@Autowired
	private UserBasicInfoService userBasicInfoService;
	@Autowired
	private ContractService contractService;
	@Autowired
	private ReportService reportService;
	
	
	static Date d = new Date();
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    public static String dateNowStr = sdf.format(d);
    public static final String pdfname = dateNowStr+"-"+System.currentTimeMillis()+".pdf";
   // public static final String pdfRoot="C:\\pdf/"+ dateNowStr+"-"+System.currentTimeMillis()+".pdf";
   public static final String pdfRoot="C:\\share\\apache-tomcat-8.0.46\\webapps\\report/"+ dateNowStr+"-"+System.currentTimeMillis()+".pdf";

   
    public  String RESULT1 = pdfRoot;
	public  String RESULT2 = "E:\\pdfFolder/coverfilled.pdf";
    
	@RequestMapping("/getContractList")
	public String selectContract(HttpServletRequest request,Model model){
		HttpSession session = request.getSession();
		User currentUser = (User) session.getAttribute("currentUser");
		UserBasicInfo userBasicInfo = userBasicInfoService.getInfoByAccount(currentUser.getUsername());
		int roleId = currentUser.getRoleid();
		if(roleId == 2)
		{
			//项目负责人，返回其负责的所属企业的所有合同
			
			List<HashMap> pepm = contractService.queryContractInfoByProjectLeaderAccount(userBasicInfo.getLoginId());
			model.addAttribute("contract", pepm);
			System.out.println("contract  "+pepm.toString());
		}
		else if(roleId == 1)
		{
			//如果是企业管理员,返回该企业所有项目负责人的合同
			//List<String> usernameList = userBasicInfoService.queryPMByEnterpriseId(userBasicInfo.getEnterpriseId());
			List<HashMap> pepm = contractService.queryAllContractInfoWithEnterprise(userBasicInfo.getEnterpriseId()/*usernameList*/);
			model.addAttribute("contract", pepm);
			System.out.println("contract  "+pepm.toString());
		}
		return "report/generateReport";
	}
	
	
	@RequestMapping(value="getContentOfContract", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getContentOfContract(HttpServletRequest request,Model model){
		int contractId = Integer.parseInt(request.getParameter("contractId"));
		HashMap<String, Object> contract = contractService.getContractInfoById(contractId);
		String json = JSONObject.toJSONString(contract);
		System.out.println(json);
		return json;
	}
	
	@RequestMapping("/createPDF")
	@ResponseBody
	public String createPDF(HttpServletRequest request,Model model) throws FileNotFoundException, SQLException, DocumentException, IOException, ParseException{
        
		String url = null;
		JSONObject json = new JSONObject();
		String end_time;
		String start_time;
		String contractId= request.getParameter("contractId");
		System.out.println("contractId  "+contractId);
		String planTime = request.getParameter("planTime");
		System.out.println("planTime  "+planTime);
/*		if(planTime == ""){
			json.put("flag", 0);//时间为空
			return json.toJSONString();
		}*/
		String[] timeList = planTime.split("年");
		String year= timeList[0];
		String month = null;
		int season = 0 ;
		int type=Integer.parseInt(request.getParameter("type"));
		System.out.println("type  "+type);
		if(type == 1){//月计划
			month = timeList[1].substring(0,2);
		}else if(type == 2){//季计划
			season = Integer.parseInt(timeList[1].substring(0,2));
		}
		String[] MonthTime={"-01-01 00:00:00","-02-01 00:00:00","-03-01 00:00:00","-04-01 00:00:00",
				"-05-01 00:00:00","-06-01 00:00:00","-07-01 00:00:00","-08-01 00:00:00","-09-01 00:00:00",
				"-10-01 00:00:00","-11-01 00:00:00","-12-01 00:00:00","-12-31 23:59:59"};
		String timeJudgeEnd;
		String timeJudgeStart;
		
		switch(type){
		case 1:
			start_time=year+MonthTime[Integer.valueOf(month)-1];
	        end_time=year+MonthTime[Integer.valueOf(month)];
	       
	        timeJudgeStart=year+"0";
	        if(month.length()==1){//logic relation is the plantime<=timeJudgeEnd && plantime>timeJudgeStart
	        	  timeJudgeEnd=year+"0"+month;//in month report check, only timeJudgeEnd is required 	
	        }else{
	        	timeJudgeEnd=year+month;//format is like: 201811  201803
	        }       
	        System.out.println("timeJudgeEnd："+timeJudgeEnd);
	        System.out.println("timeJudgeStart："+timeJudgeStart);
	        if(CreatePDFJuge.CreatPdfJuge(contractId,timeJudgeStart,timeJudgeEnd,type)){
	        	System.out.println("can create pdf");
	    		Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	    		String time = "月";
	    		OutputStream pdfFileOutputStream = new FileOutputStream(new File(RESULT1));
	    		PdfWriter writer=PdfWriter.getInstance(document,pdfFileOutputStream);
	    		document.open();		
	    		url =  new Cover().CreatCover(writer,RESULT1,pdfname,document,contractId,end_time,start_time,time);
//	    		new Cover().manipulatePdf(RESULT1, RESULT2);
	    		document.close();
	    		System.out.println(year+"   "+month);
	    		reportService.insertReport(contractId,type,year,month,season,url,pdfname);
	    		json.put("flag", 1);//完成
	    		System.out.println("wancheng");
	        }else{
	        	json.put("flag", 2);//失败
	        }
	        break;
		case 2:
			if(season==4){
				timeJudgeEnd=year+"12";
				timeJudgeStart=year+"10";
			}else{
				timeJudgeEnd=year+"0"+Integer.valueOf(season*3).toString();
				timeJudgeStart=year+"0"+Integer.valueOf(season*3-2).toString();
			}
	        end_time = year+MonthTime[season*3];
	        start_time = year+MonthTime[season*3-3];
	        System.out.println("start_time："+start_time);
	        System.out.println("end time："+end_time);
	        if(CreatePDFJuge.CreatPdfJuge(contractId,timeJudgeStart,timeJudgeEnd,type)){
	        	System.out.println("can create pdf");
	        	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	    		String time = "季";
	    		OutputStream pdfFileOutputStream = new FileOutputStream(new File(RESULT1));
	    		PdfWriter writer=PdfWriter.getInstance(document,pdfFileOutputStream);
	    		document.open();		
	    		url = new Cover().CreatCover(writer,RESULT1,pdfname,document,contractId,end_time,start_time,time);
//	    		new Cover().manipulatePdf(RESULT1, RESULT2);
	    		document.close();
	    		reportService.insertReport(contractId,type,year,month,season,url,pdfname);
	    		json.put("flag", 1);//时间为空
	        }else{
	        	json.put("flag", 2);//时间为空
	        }
	        break;
		case 3:
			timeJudgeEnd=year+"12";
			timeJudgeStart=year+"01";
	        end_time = year+MonthTime[12];      
	        start_time = year+MonthTime[0];
	        System.out.println("start_time："+start_time);
	        System.out.println("end_time："+end_time);
	        if(CreatePDFJuge.CreatPdfJuge(contractId,timeJudgeStart,timeJudgeEnd,type)){
	        	System.out.println("can create pdf");
	        	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	    		String time = "年";
	    		OutputStream pdfFileOutputStream = new FileOutputStream(new File(RESULT1));
	    		PdfWriter writer=PdfWriter.getInstance(document,pdfFileOutputStream);
	    		document.open();		


                url =  new Cover().CreatCover(writer,RESULT1,pdfname,document,contractId,end_time,start_time,time);

//	    		new Cover().manipulatePdf(RESULT1, RESULT2);
	    		document.close();
	    		reportService.insertReport(contractId,type,year,month,season,url,pdfname);
	    		json.put("flag", 1);//时间为空
	        }else{
	        	json.put("flag", 2);//时间为空
	        	}
	        break;
		default:
            System.out.println("undefined number");
            break;
		}



		return json.toJSONString();
		
	}
	
	@RequestMapping(value="getReportList", produces = "text/html;charset=UTF-8")
	@ResponseBody
    public String getReportOfCompany(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException{
		
		int contractId = Integer.parseInt(request.getParameter("contractId"));
		List<HashMap<String, Object>> report = new ArrayList<HashMap<String, Object>>();
		report = reportService.getReportByContractId(contractId);
        System.out.println(JSONArray.toJSONString(report));
    	return JSONArray.toJSONString(report);
    }
	
	@RequestMapping("/getReportListOfContract")
    public String getReportListOfContract(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException{
		ObjectMapper objectMapper = new ObjectMapper();
		int contractId = Integer.parseInt(request.getParameter("contractId"));
		List<HashMap<String, Object>> report = new ArrayList<HashMap<String, Object>>();
		report = reportService.getReportByContractId(contractId);
        System.out.println(report.toString());
        model.addAttribute("content", objectMapper.writeValueAsString(report));
    	return "maintenanceProject/viewReport";
    }
	@RequestMapping("/getContract")
	public String selectContractList(HttpServletRequest request,Model model){
		HttpSession session = request.getSession();
		User currentUser = (User) session.getAttribute("currentUser");
		UserBasicInfo userBasicInfo = userBasicInfoService.getInfoByAccount(currentUser.getUsername());
		int roleId = currentUser.getRoleid();
		if(roleId == 2)
		{
			//项目负责人，返回其负责的所属企业的所有合同
			
			List<HashMap> pepm = contractService.queryContractInfoByProjectLeaderAccount(userBasicInfo.getLoginId());
			model.addAttribute("contract", pepm);
			System.out.println("contract  "+pepm.toString());
		}
		else if(roleId == 1)
		{
			//如果是企业管理员,返回该企业所有项目负责人的合同
			//List<String> usernameList = userBasicInfoService.queryPMByEnterpriseId(userBasicInfo.getEnterpriseId());
			List<HashMap> pepm = contractService.queryAllContractInfoWithEnterprise(userBasicInfo.getEnterpriseId()/*usernameList*/);
			model.addAttribute("contract", pepm);
			System.out.println("contract  "+pepm.toString());
		}
		return "report/searchReport";
	}

}
